# CardManager.gd (节点脚本，挂载到卡牌区根节点)
extends Node2D
class_name CardManager

@export var layer_offset := Vector2(120, 80)  # 层级间距
@export var base_card_size := Vector2(100, 150)  # 基础卡牌尺寸

static var scenic_card_layer: Dictionary = {}  # Key: layer层数, Value: Array[CardBase]子卡牌列表
static var scenic_card_hierarchy: Dictionary = {}  # Key: 父节点的CardBase, Value: Array[CardBase]子卡牌列表

var card_generator :CardGenerator 
static var card_being_dragged: CardBase
var card_click_check # 点击释放一致性校验
var card_tmp_pos: Vector2 # 卡牌移动后位置校验
var mouse_tmp_pos: Vector2 # 鼠标点击位置校验

func _ready() -> void:
	card_generator = CardGenerator.new()
	GlobalConstants.viewport_size = get_viewport_rect().size
	card_generator.prewarm_pool()
	_clear_old_data()
	card_generator.generate_scenic_card_layers(self)  # 场景加载后立即生成景区卡
	card_generator.generate_enemy_card(self) # 场景加载后立即生成对战卡

func _clear_old_data():
	# 清空旧数据
	scenic_card_hierarchy.clear()
	for child in get_children():
		child.queue_free()
	
func _process(_delta: float) -> void:
	if card_being_dragged :
		var mouse_pos = get_global_mouse_position()
		card_being_dragged.position = Vector2(clamp(mouse_pos.x, 0, GlobalConstants.viewport_size.x),
		clamp(mouse_pos.y, 0, GlobalConstants.viewport_size.y))
	
func _input(event: InputEvent) -> void:
	if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT:
		var card = raycast_check_for_card()#检索点击时最上层卡牌
		if event.pressed :
			if card :
				card_click_check = card
				card_tmp_pos = card.position
				mouse_tmp_pos = get_global_mouse_position()
				_start_drag(card)
		else :
			# 通过EventBus发送点击事件
			if card :
				if card == card_click_check and get_global_mouse_position() == mouse_tmp_pos:
					_EventBus.card_clicked.emit(card)
			if card_being_dragged :
				_finish_drag()
			# 标记事件已处理，阻止后续传递
			get_viewport().set_input_as_handled()
			
func raycast_check_for_card():
	var space_state = get_world_2d().direct_space_state
	var parameters = PhysicsPointQueryParameters2D.new()
	parameters.position = get_global_mouse_position()
	parameters.collide_with_areas = true
	#parameters.collision_mask = 1
	var collider
	var last_layer_com = 0
	var result = space_state.intersect_point(parameters)
	if result.size()> 0:
		for res in result :
			if last_layer_com < res.collider.collision_layer :
				collider = res.collider
				last_layer_com = res.collider.collision_layer
		#print("result: %s ,max layer collider_id: %s" % [result,collider_id])
		return collider
	return null
	
func _start_drag(card:CardBase) :
	card_being_dragged = card
	card.scale = GlobalConstants.BASE_SCALE
	
func _finish_drag() :
	card_being_dragged.position = card_tmp_pos
	card_being_dragged.scale = GlobalConstants.HIGHLIGHT_SCALE
	card_being_dragged = null

	
